package com.hu.biz.util.lock;


import com.hu.common.util.adm.E2s;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName RenewTask
 * @Description 续租锁任务
 * @author 355760
 **/
public class RenewTask extends Thread {

    private static final Logger LOGGER = LoggerFactory.getLogger(RenewTask.class);

    public volatile boolean isRunning = true;

    /**
     * 过期时间，单位毫秒
     */
    private final Long ttl;

    private final IRenewalHandler call;

    public RenewTask(IRenewalHandler call, Long ttl) {
        this.ttl = ttl <= 0 ? 10 : ttl;
        this.call = call;
    }

    @Override
    public void run() {
        while (isRunning) {
            try {
                // 1、续租，刷新值
                call.callBack();
                LOGGER.debug("续租成功!");
                // 2、三分之一过期时间续租
                TimeUnit.MILLISECONDS.sleep(this.ttl / 3);
            } catch (Exception e) {
                LOGGER.error("[RenewTask exception:] {}", E2s.exception2String(e));
                close();
            }
        }
    }

    public void close() {
        isRunning = false;
    }
}
